import { useEmit } from "./emit";
import { isObject } from "./utils";

export const ApiJson = "apijson";
export const ApiContentMenu = "apicontentmenu";

const ExtensionEventType = "OpenApiViewEvent";

class ExtensionEvent {
  type = ExtensionEventType;

  constructor(name, data) {
    this.name = name;
    this.data = data;
  }
}

const emit = useEmit(ExtensionEventType);

chrome.runtime.onMessage.addListener((event, sender) => {
  if (!isObject(event) || event.type !== ExtensionEventType) return;

  emit.emit(event.name, event.data, sender);
});

export function sendMessage(name, data, tabId) {
  const event = new ExtensionEvent(name, data);
  if (tabId) chrome.tabs.sendMessage(tabId, event);
  else chrome.runtime.sendMessage(chrome.runtime.id, event);
}

export function onMessage(name, fn, once) {
  emit.on(name, fn, once);
}
